import sqlite3
import sys
from os import remove
from os.path import join, exists
from shutil import copy2


import re

__all__ = ['BizObject']

rule_tuple = (
	('[ml]ouse$', '([ml])ouse$', '\\1ice'),
	('child$', 'child$', 'children'),
	('booth$', 'booth$', 'booths'),
	('foot$', 'foot$', 'feet'),
	('ooth$', 'ooth$', 'eeth'),
	('l[eo]af$', 'l([eo])af$', 'l\\1aves'),
	('sis$', 'sis$', 'ses'),
	('man$', 'man$', 'men'),
	('ife$', 'ife$', 'ives'),
	('eau$', 'eau$', 'eaux'),
	('lf$', 'lf$', 'lves'),
	('[sxz]$', '$', 'es'),
	('[^aeioudgkprt]h$', '$', 'es'),
	('(qu|[^aeiou])y$', 'y$', 'ies'),
	('$', '$', 's')
)


def regex_rules(rules=rule_tuple):
	for line in rules:
		pattern, search, replace = line
		yield lambda word: re.search(pattern, word) and re.sub(search, replace, word)


def plural(noun):
	for rule in regex_rules():
		result = rule(noun)
		if result:
			return result
			
			
class GenericObject:
	def __init__(self,model,conn):
		self.conn 	= conn
		self.model	= model
		self.table	= plural(model)

	def Add( self, values ):
		c		= self.conn.cursor()
		fields	= ",".join(values)
		sql = "INSERT INTO " + self.table +" ("+fields+")" + "VALUES("
		
		valargs	= []
		for value in values:
			valargs.append( ":"+value )
			
		sql += ",".join(valargs)
		sql += ")"
		
		c.execute(sql, values)
		self.conn.commit()
		
		return c.lastrowid

	def Update( self, oid, values ):
		c		= self.conn.cursor()
		sql = "UPDATE " + self.table +" SET "
		
		valargs	= []
		for value in values:
			valargs.append( value+"=:"+value )
			
		sql += ",".join(valargs)
		sql += " WHERE id=" + str(oid)
		
		c.execute(sql, values)
		self.conn.commit()

	def GetObjectList( self, criteria ):
		c	= self.conn.cursor()
		c.execute( "SELECT id FROM " + self.table +" WHERE "+criteria  )
		idList	= list()
		for row in c:
			idList.append( row[0] )
		return idList
		
	def GetObjectCount( self, criteria ):
		c	= self.conn.cursor()
		c.execute("SELECT count(id) FROM " + self.table +" WHERE "+criteria  )
		row	= c.fetchone()		
		return row[0]
		
	def Find( self, oid ):
		return (len(self.FindBy("id", oid))!=0)
		
	def FindBy( self, field, value ):
		t   = (value,)
		c	= self.conn.cursor()
		c.execute("SELECT id FROM " + self.table +" WHERE "+field+"=?", t  )
		idList	= list()
		for row in c:
			idList.append( row[0] )
		return idList
	
	def Set( self, oid, field, value ):
		t   = (value,oid)
		c	= self.conn.cursor()
		c.execute("UPDATE " + self.table +" SET "+field+"=? WHERE id=?", t  )
		self.conn.commit()
				
	def Get( self, oid, field ):
		t   = (oid,)
		c	= self.conn.cursor()
		c.execute("SELECT "+field+" FROM " + self.table +" WHERE id=?", t  )
		row	= c.fetchone()
		if row == None:
			return None
		return row[0]

	def GetBy( self, findfield, field, value ):
		t   = (value,)
		c	= self.conn.cursor()
		c.execute("SELECT "+findfield+" FROM " + self.table +" WHERE "+field+"=?", t  )
		idList	= list()
		for row in c:
			idList.append( row[0] )
		return idList
		
	def Delete( self, oid ):
		c	= self.conn.cursor()
		t = (oid,)
		c.execute("DELETE FROM "+ self.table +" WHERE id IN(?)", t )
		self.conn.commit()

class ProcessObject(GenericObject):
	def __init__(self,model):
		conn = sqlite3.connect( "../process.s3db" );
		GenericObject.__init__(self,model,conn)
		
class ContactObject(GenericObject):
	def __init__(self,model):
		conn = sqlite3.connect( "../contact.s3db" );
		GenericObject.__init__(self,model,conn)
		


